<?php
include_once "book.php";
include_once "settings.php";

function shingleCalc($stringToProcced, $stopWords, $amount)
{

	$stringEncoding=mb_detect_encoding($stringToProcced);

	$stringToProcced = mb_strtolower($stringToProcced,$stringEncoding);

	//strip punctuation, numbers, EOL, tabs. words 1 symbol, words - 2 symbols, words - 3 symbols
	$stringToProcced = preg_replace('/(\p{P}|\p{N}|\p{Zs}|\r|\n|\t|\b.\b|\b..\b)+/u', " ", $stringToProcced);


//	$stringToProcced2Array = explode(" ",$stringToProcced);

	$stringToProcced2Array = array_diff(explode(" ",$stringToProcced), $stopWords);


	$stringToProcced2Array = array_values($stringToProcced2Array);

	for ($i = 9; $i < sizeof($stringToProcced2Array); $i++)
	{
		$hash[] = md5($stringToProcced2Array[$i-9] . $stringToProcced2Array[$i-8] . $stringToProcced2Array[$i-7] . $stringToProcced2Array[$i-6] . $stringToProcced2Array[$i-5] .
				$stringToProcced2Array[$i-4] . $stringToProcced2Array[$i-3] . $stringToProcced2Array[$i-2] . $stringToProcced2Array[$i-1] . $stringToProcced2Array[$i-0]) ;
	}

	asort($hash) ;

	$hash = array_slice($hash, 0, $amount);

return $hash ;
}

function getSimilarBooks($bookArray)
{
	$matchArray[] ="" ;

	foreach ( $bookArray as $outKey=>$outValue)
		foreach ( $bookArray as $inKey=>$inValue)
		{
			if ($outKey == $inKey) { continue; }

			$result = array_diff(explode(" ",$outValue), explode(" ",$inValue)) ;
			$percetnageResult = round((100 - (sizeof($result)*100)/10)) ;

			if ($percetnageResult > 50) //some kind of percentage of similarity - 50%
				{
					if (isset($matchArray[$outKey]))
					{
						$matchArray[$outKey] = $matchArray[$outKey] . "," . $inKey ;
					}
					else
					{
						$matchArray[$outKey] = $inKey ;
					}
					//echo $outKey ." is similar to ". $inKey . " match persentage - " . $percetnageResult . "% " . PHP_EOL ;
				}


		}
	return $matchArray ;



}

/*
$connection = new mysqli($host, $user, $password, $dbname, $port, $socket);
if ($connection->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); }
$connection->set_charset("utf8");


// get shingle Hash table into array

$res = $connection->query('select * from book_shingle');

while ($currentHashRecord = $res->fetch_array())

{
	$bookArray[$currentHashRecord[0]] = $currentHashRecord[1] ; //bookID - array index ; book_shingle_value - array value
}



print_r (getSimilarBooks($bookArray)) ;

echo "done";
*/

?>

